//
//  JMBaseRequest.m
//  JMBaseProject
//
//  Created by Liuny on 2020/8/8.
//  Copyright © 2020 liuny. All rights reserved.
//

#import "JMBaseRequest.h"
#import "BaseViewController.h"
#import "UIWindow+CurrentViewController.h"
#import "JMLoginVC.h"

@interface JMBaseRequest ()

@end

@implementation JMBaseRequest

+(JMBaseRequest *)sharedInstance{
    static JMBaseRequest *instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone:NULL] init];
    });
    return instance;
}

+(id)allocWithZone:(struct _NSZone *)zone{
    return [self sharedInstance];
}

-(id)copyWithZone:(NSZone *)zone{
    return self;
}


/// Post请求
/// @param url 地址
/// @param params 参数
/// @param success 成功
/// @param fail 失败
-(void)requestBasePost:(NSString *)url
                params:(NSDictionary *)params
               success:(SuccessBlock)success
                  fail:(FailBlock)fail{
   
    __block BaseViewController *curVC;
    BOOL isBehavor = (
                      [url containsString:@"api/common/user-behavior-record"]
                      || [url containsString:@"user-behavior-track"]
                      || [url containsString:@"caradurismos/borneados/emancipes"]
                      || [url containsString:@"caradurismos/tanateaseis/desborde"]
                      || [url containsString:@"caradurismos/dactilografa/despajaremos"]
                      || [url containsString:@"caradurismos/profanarias/exclamatoria"]
                      || [url containsString:@"caradurismos/lobezno/invitaren"]
                      || [url containsString:@"caradurismos/dactilografa/metoposcopia"]
                      || [url containsString:homePop]
                      || [url containsString:loginSendSms]
                      );
    if (!isBehavor) {
        [JMProgressHelper loadingInWindowWithMessage:nil];
    }
    JMRequestManager*manager = JMRequestManager.sharedManager;
    [manager POST:url parameters:params completion:^(JMBaseResponse *response) {
        
        [JMProgressHelper hidenLoadingInWindow];
        
        if(response.statusCode!=200){
            if(response.statusCode==-1){
                [JMProgressHelper toastInWindowWithMessage:@"Silahkan login dulu"];
                JMLoginVC *login = [JMLoginVC new];
                [UIApplication sharedApplication].keyWindow.rootViewController = login;
            }
            if(response.statusCode==99){
                [JMProgressHelper toastInWindowWithMessage:response.errorMsg];
            }
            if(response.statusCode==500){
                [JMProgressHelper toastInWindowWithMessage:@"Sistem sedang mengalami kendala, mohon mencoba kembali lagi nanti"];
            }
            NSString *errMsg = response.errorMsg;
            if([errMsg isKindOfClass:NSString.class]&&response.statusCode!=-1001&&fail!=nil){
                [JMProgressHelper hidenLoadingInWindow];
                fail(errMsg);
            }
        }else{
            if(success){
                NSDictionary *dataDic = response.responseObject[@"data"];
                success(dataDic,nil);
            }
        }
    }];
}
-(void)requestBasePost:(NSString *)url
                params:(NSDictionary *)params
               successResult:(SuccessBlock)success
                  fail:(FailBlock)fail{
   
    BaseViewController *curVC = UIWindow.jm_currentViewController;
    JMRequestManager*manager;
    manager = JMRequestManager.sharedManager;
    [manager POST:url parameters:params completion:^(JMBaseResponse *response) {
        if(response.statusCode!=200){
            if(response.statusCode==-1){
                [JMProgressHelper toastInWindowWithMessage:@"¡Favor de iniciar sesión!"];
                BaseViewController *login = [BaseViewController new];
                [UIApplication sharedApplication].keyWindow.rootViewController = login;
            }
            if(response.statusCode==99){
                [JMProgressHelper toastInWindowWithMessage:response.responseObject[@"message"]];
            }
            if(response.statusCode==500){
                [JMProgressHelper toastInWindowWithMessage:@"Red ocupada"];
            }
            
            NSString *errMsg = response.responseObject[@"message"];
            if([errMsg isKindOfClass:NSString.class]){
                fail(errMsg);
            }

        }else{
            if(success){
                NSDictionary *dataDic = response.responseObject;
                success(dataDic,nil);
            }
        }
    }];
}
/// POST表单上传图片
/// @param url api地址
/// @param params 参数
/// @param pictures 图片数据，key：图片data value：接口字段_名字
/// @param success 成功
/// @param fail 失败
-(void)requestUploadBasePost:(NSString *)url
                      params:(NSDictionary *)params
                    pictures:(UIImage*)picture
                     success:(void(^)(NSDictionary *data))success
                        fail:(FailBlock)fail{
    [JMProgressHelper loadingInWindowWithMessage:nil];
    NSURL *URL = [NSURL URLWithString: BasePostRequestUrl(url)];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    [request setHTTPMethod:@"POST"];
    
    // 设置请求头
    [request setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    [request setValue:bundleId forHTTPHeaderField:@"x-package-name"];
    [request setValue:JMProjectManager.sharedJMProjectManager.loginUser.token forHTTPHeaderField:@"x-auth-token"];
    [request setValue:@"1.0.0" forHTTPHeaderField:@"x-version"];
    
    // 生成一个随机的boundary字符串
    NSString *boundary = [self generateBoundaryString];

    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request setValue:contentType forHTTPHeaderField:@"Content-Type"];

    NSMutableData *formData = [NSMutableData data];
    [formData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [formData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [formData appendData:[@"Content-Disposition: form-data; name=\"photo\"; filename=\"photo.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [formData appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
   
    NSData *imgData =  [self compressImage:picture toMaxSize:300];
    if ([url containsString:@"penetrador/amortiguado/terracearas"] ||[url containsString:@"penetrador/amortiguado/desinflamaran"] ) {
        [JMCommonMethod uploadStatistics:@"inculpare" actionType:@"acescencias" parameters:nil];
    }
    [formData appendData:imgData];
    [formData appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [formData appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [request setHTTPBody:formData];
    // 创建NSURLSession对象并发送请求
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        [JMProgressHelper hidenLoadingInWindow];
        if (error == nil && data != nil) {
            NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
            NSString *code = content[@"code"];

            if (code.intValue == 200) {
                if (content) {
                    NSDictionary *data = content[@"data"];
                    NSDictionary *tongDunOCRResponseEntity = data[@"tongDunOCRResponseEntity"];
                    NSDictionary *idCardData = tongDunOCRResponseEntity[@"idCardData"];

                    NSString *photoName = data[@"photoName"];
//                    NSString *url = data[@"url"];
                    NSString *fullName = idCardData[@"name"];
                    NSString *idNumber = idCardData[@"nik"];
                    NSString *livenessId = data[@"livenessId"];

                    NSLog(@"%@",content);
                    success(data);
                }
            }else{
                NSString *message = content[@"message"];
                if (message) {
                    [JMProgressHelper toastInWindowWithMessage:message];
                    fail(message);
                }
            }
        }
    }];

    [task resume];
}
- (NSData *)compressImage:(UIImage *)image toMaxSize:(NSUInteger)maxSizeInKB {
    CGFloat compressionQuality = 1.0;
    NSData *compressedImageData = UIImageJPEGRepresentation(image, compressionQuality);
    
    while ([compressedImageData length] > maxSizeInKB * 1024 && compressionQuality > 0.0) {
        compressionQuality -= 0.1;
        compressedImageData = UIImageJPEGRepresentation(image, compressionQuality);
    }
    if (JMProjectManager.sharedJMProjectManager.appConfig.isfront) {
        [JMCommonMethod uploadStatistics:@"inculpare" actionType:@"desmigare" parameters:@{@"size":@(compressedImageData.length)}];
    }

    return compressedImageData;
}
/// POST表单上传图片
/// @param url api地址
/// @param params 参数
/// @param pictures 图片数据，key：图片data value：接口字段_名字
/// @param success 成功
/// @param fail 失败
// 生成随机boundary字符串的函数
- (NSString *)generateBoundaryString {
    JMAppConfig *config = JMProjectManager.sharedJMProjectManager.appConfig;
    return [NSString stringWithFormat:@"Boundary-%@", config.uuidString];
}

@end
